<style lang="less">
  .short-barge {
    height: 100%;
    display: flex;
    .split_order {
      color: #FF4949;
    }
    .split_cancel {
      color: #D84C29;
    }
    .split_notice {
      color: #D84C29;
    }
    .invalid {
      .el-input__inner {
        border-color: red;
      }
    }
    .left {
      flex: 0 0 400px;
      display: flex;
      flex-direction: column;
      width: 400px;
      .tj {
        border: 1px solid #ccc;
        padding: 10px 10px 0 10px;
        .circle {
          width: 20px;
          height: 20px;
          background-color: #20a0ff;
          text-align: center;
          color: white;
          border-radius: 10px;
          margin: 0 5px 10px 0;
          display: inline-block;
        }
      }
      .se-vehicle {
        padding: 10px;
        background-color: #f2f2f2;
        .el-select {
          width: 330px;
          .el-input {
            .el-input__inner {
              height: 30px;
            }
          }
        }
      }
      .el-table {
        flex: 1;
        overflow-y: auto;
        .el-icon-check {
          display: none;
        }
        .current-row {
          .el-icon-check {
            display: inline-block;
          }
        }

      }
    }
    .center {
      margin-left: 10px;
      flex: 1;
      overflow-x: auto;
      display: flex;
      flex-direction: column;
      .el-collapse-item__header {
        .el-collapse-item__header__arrow {
          float: left;
          margin-top: 15px;
        }
        .active_tab_item{
          color: #20a0ff;
        }
      }
      .el-date-editor {
        width: 100%;
      }
      .el-collapse-item:last-child {
        margin-bottom: 0px;
      }
      .is-active {
        flex: 1;
        overflow-y: hidden;
        flex: 1;
        display: flex;
        flex-direction: column;
        .el-collapse-item__wrap {
          flex: 1;
          display: flex;
          flex-direction: column;
          .el-collapse-item__content {
            flex: 1;
            display: flex;
            flex-direction: column;
            .el-tab-pane {
              flex: 1;
              display: flex;
              flex-direction: column;
              .el-table {
                flex: 1;
                overflow-y: auto;
              }
            }
            .el-table {
              flex: 1;
              overflow-y: auto;
            }
          }
        }
      }
    }
  }
  #addVehicleTemporaryDialog{
    .el-dialog{
      .el-dialog__body{
        padding: 20px 0px 10px 0px;
      }
    }
  }
</style>

<template>
  <section class="short-barge">
    <div class="left">
      <div class="tj">
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="circle">车</div>
            {{left.goodsVehicleStatistics.vehicleNum}}辆
          </el-col>
          <el-col :span="8">
            <div class="circle">票</div>
            {{left.goodsVehicleStatistics.orderStatistics.orderSum}}单
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="circle">件</div>
            {{left.goodsVehicleStatistics.orderStatistics.total}}件
          </el-col>
          <el-col :span="8">
            <div class="circle">重</div>
            {{left.goodsVehicleStatistics.orderStatistics.totalWeight.toFixed(2)}}吨
          </el-col>
          <el-col :span="8">
            <div class="circle">体</div>
            {{left.goodsVehicleStatistics.orderStatistics.totalVolume.toFixed(2)}}方
          </el-col>
        </el-row>
      </div>
      <el-col :span="24" class="se-vehicle">
        <el-select v-model="vehicleIds"
                      multiple
                      filterable
                      remote
                      placeholder="请输入车牌号码"
                      :remote-method="searchVehicle"
                      :loading="left.searchVehicleLoading">
          <el-option
            v-for="item in left.vehicles"
            :key="item.id"
            :label="item.plateNumber"
            :value="item.id">
          </el-option>
        </el-select>
        <el-button type="primary" icon="el-icon-plus" @click="addVehicle"></el-button>
      </el-col>
      <el-table :data="left.vehicleTableData"
                height="100%"
                highlight-current-row
                @current-change="handleCurrentChange"
                border
                v-loading="left.listLoading">
        <el-table-column
          label="选中"
          width="70">
          <template slot-scope="scope">
            <i class="el-icon-check"></i>
          </template>
        </el-table-column>
        <el-table-column
          prop="plateNumber" label="车牌号" width="100">
        </el-table-column>
        <el-table-column show-overflow-tooltip label="司机">
          <template slot-scope="scope">
            <div v-for="(item,index) in scope.row.driverInfos" :key="index">{{item.name}}/{{item.phone}}</div>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="typeName" label="运力类型" width="120">
          <template slot-scope="scope">
            {{ scope.row.length }}米/{{scope.row.deadweight}}吨
          </template>
        </el-table-column>
        <el-table-column prop="locationAddr" label="位置" width="200">
        </el-table-column>
      </el-table>
      <el-dialog title="新增临时车辆" :visible.sync="left.addVehicleDialogVisible"
        size="tiny" id="addVehicleTemporaryDialog">
        <el-form ref="addVehicleForm" :model="left.vehicleForm" label-width="40%">
          <el-form-item label="车牌号"
                        :rules="[
                          { required: true, message: '请输入车牌号', trigger: 'blur' },
                          { max: 10, message: '长度不能大于10个字符', trigger: 'blur' }
                        ]"
                        prop="plateNumber">
            <el-input v-model="left.vehicleForm.plateNumber" style="width: 60%"></el-input>
          </el-form-item>
          <el-form-item label="司机姓名"
                        :rules="[
                          { required: true, message: '请输入司机姓名', trigger: 'blur' },
                          { max: 20, message: '长度不能大于20个字符', trigger: 'blur' }
                        ]"
                        prop="name">
            <el-input v-model="left.vehicleForm.name"  style="width: 60%"></el-input>
          </el-form-item>
          <el-form-item label="联系方式"
                        :rules="[
                          { required: true, message: '请输入联系方式', trigger: 'blur' },
                          { max: 13, message: '长度不能大于13个字符', trigger: 'blur' }
                        ]"
                        prop="phone">
            <el-input v-model="left.vehicleForm.phone"  style="width: 60%"></el-input>
          </el-form-item>
        </el-form>
        <el-row style="border: 1px solid #E9E9E9;height: 140px">
          <div style="width: 80%;margin: 0px auto">
            <el-col :span="24">
              <p style="font-weight: 700;color: grey">历史使用车辆</p>
            </el-col>
            <div style="width: 80%">
                  <el-col :span="8" style="padding-bottom: 10px"  v-for="(item,index) in left.vehicleTableDataTemporary" :key="index">
                    <el-button style="background-color: #E9E9E9;width: 90%" @click="selectVehicleInfoTemporary(item)">{{item.plateNumber}}</el-button>
                  </el-col>
            </div>
          </div>
        </el-row>
        <span slot="footer" class="dialog-footer">
          <el-button @click="left.addVehicleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveVehicle">确 定</el-button>
        </span>
      </el-dialog>
    </div>
    <el-collapse class="center" v-model="center.activeNames" accordion>
      <ue-el-collapse-item title="待接货列表" name="1">
        <template slot="title">
          <div class="el-tabs__nav">
            <div class="el-tabs__active-bar"
                 :style="{transform:(activeElTabsItem==='待接货列表'? 'translateX(7px)':'translateX(115px)')}"
                 style="width: 88px;"></div>
            <div class="el-tabs__item" :class="{ active_tab_item: (activeElTabsItem==='待接货列表') }"
                 @click="activeElTabsItem='待接货列表'">待接货列表
            </div>
            <div class="el-tabs__item" :class="{ active_tab_item: (activeElTabsItem==='待配送列表') }"
                 @click="activeElTabsItem='待配送列表'">待配送列表
            </div>
          </div>
        </template>
        <div class="el-tab-pane" v-show="activeElTabsItem==='待接货列表'">
          <ue-search-bar empty-text="receiving组查询条件未配置" ref="ueSearchBarReceiving" v-model="center.orderSearchCondition" :data="querysReceiving" label-width="100px">
          </ue-search-bar>
          <!-- 操作 -->
          <el-col :span="24" style="margin-bottom: 10px">
            <el-col :span="8">
              <el-switch
                v-model="center.orderType"

                >
              </el-switch>
              <el-button type="primary" @click="addShortTask" :disabled="orderSels.length ===0 || !isIssued || isTemporaryDriver">
                添加
              </el-button>
              <el-button type="primary" @click="addShortTaskAndIssued"
                         :disabled="orderSels.length ===0 || !isIssued">添加并下发
              </el-button>
              <el-button type="primary" @click="confirmSplit"
                         :disabled="selectedOrder === null || selectedOrder.type==='group' || selectedOrder.pid !== null || selectedOrder.childrenNum !== null">
                拆分订单
              </el-button>
              <el-button type="primary" @click="removeSplit"
                         :disabled="selectedOrder === null || selectedOrder.type==='group' || selectedOrder.childrenNum === null || !isCancleSplitShortTask">
                取消拆分
              </el-button>

            </el-col>
            <el-col :span="8">
            <span
              style="font-size: 16px;margin-left: 50px;">当前选中：{{totalAmount}}件 {{totalWeight.toFixed(2)}}吨 {{totalVolume.toFixed(2)}}方</span>
            </el-col>
            <el-col :span="8" style="text-align: right">
              <el-button type="primary" @click="shortBargeExpress"
              >
                导出
              </el-button>
              <el-button type="primary" @click="resetOrderCondition">重置</el-button>
              <el-button type="primary" @click="searchOrder">查询</el-button>
            </el-col>
          </el-col>

          <!--列表-->
          <ue-el-table
            ref="orderTable"
            :data="center.orderTableData" highlight-current-row border
            @selection-change="selsOrderChange"
            @select="orderSelect"
            height="100%"
            @current-change="handleOrderCurrentChange"
            :row-class-name="tableRowClassName"
            v-loading="center.orderListLoading">
            <el-table-column fixed type="selection" width="55">
            </el-table-column>
            <ue-el-table-tree-column fixed
                                     :remote="remote"
                                     label="订单号"
                                     child-num-key="num"
                                     width="250">
              <template slot-scope="scope">
                <a style="cursor: pointer;text-decoration:underline;"  @click="orderDetail(scope.row)">{{scope.row.label}}</a>
              </template>
            </ue-el-table-tree-column>
            <el-table-column show-overflow-tooltip prop="order.shipmentsDate" label="发运日期" width="180">
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="order.extractDateTime" label="提货日期&时间" width="200">
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="memberUserName" label="客户" width="80">
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="order.shipmentsContactName" label="发货人" width="80">
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="order.shipmentsRegion" label="发货区域" width="160">
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="order.shipmentsAddress" label="发货地址" width="160">
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="order.sendContactName" label="收货人" width="80">
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="order.sendRegion" label="收货区域" width="160">
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="order.sendAddress" label="收货地址" width="160">
            </el-table-column>
            <el-table-column fixed="right" show-overflow-tooltip prop="order.orderCargos" label="件重体" width="170"
                             :formatter="formatterOrderCargos">
            </el-table-column>
            <el-table-column show-overflow-tooltip  width="100" prop="order.remark" label="备注">
            </el-table-column>
          </ue-el-table>
        </div>
        <div class="el-tab-pane" v-show="activeElTabsItem==='待配送列表'">
          <ue-search-bar empty-text="distribution组查询条件未配置" ref="ueSearchBaristribution" v-model="center.pendingDeliverySearchCondition" :data="querysDistribution" label-width="100px">
          </ue-search-bar>
          <el-col :span="24" style="margin-bottom: 10px">
            <el-col :span="8">
              <el-switch
                v-model="center.pendingDeliveryType"

                >
              </el-switch>
              <el-button type="primary" @click="addPendingDeliveryShortTask"
                         :disabled="pendingDeliverySels.length ===0 || !isIssued || isTemporaryDriver">添加
              </el-button>
              <el-button type="primary" @click="addPendingDeliveryShortTaskAndIssued"
                         :disabled="pendingDeliverySels.length ===0 || !isIssued">添加并下发
              </el-button>
              <el-button type="primary" @click="pendingDeliveryConfirmSplit"
                         :disabled="selectedPendingDeliveryShortTask === null || selectedPendingDeliveryShortTask.type==='group' || selectedPendingDeliveryShortTask.pid !== null || selectedPendingDeliveryShortTask.childrenNum !== null">
                拆分订单
              </el-button>
              <el-button type="primary" @click="removePendingDeliverySplit"
                         :disabled="selectedPendingDeliveryShortTask === null || selectedPendingDeliveryShortTask.type==='group' || selectedPendingDeliveryShortTask.childrenNum === null || !isCancleSplitPendingDeliveryShortTask">
                取消拆分
              </el-button>
            </el-col>
            <el-col :span="8">
            <span
              style="font-size: 16px;margin-left: 50px;">当前选中：{{pendingDeliveryTotalAmount}}件 {{pendingDeliveryTotalWeight.toFixed(2)}}吨 {{pendingDeliveryTotalVolume.toFixed(2)}}方</span>
            </el-col>
            <el-col :span="8" style="text-align: right">
              <el-button type="primary" @click="waitShortBargeExpress" >
                导出
              </el-button>
              <el-button type="primary" @click="resetPendingDeliveryShortTaskCondition">重置</el-button>
              <el-button type="primary" @click="searchPendingDeliveryShortTask">查询</el-button>
            </el-col>
          </el-col>

          <ue-el-table
            ref="pendingDeliveryTable"
            :data="center.pendingDeliveryTableData" highlight-current-row border
            @selection-change="pendingDeliveryChange"
            @select="pendingDeliverySelect"
            height="100%"
            :row-class-name="tableRowClassName"
            @current-change="handlePendingDeliveryCurrentChange"
            v-loading="center.pendingDeliveryLoading">
            <el-table-column fixed type="selection" width="55">
            </el-table-column>
            <ue-el-table-tree-column fixed
                                     :remote="remotePendingDelivery"
                                     prop="label"
                                     label="订单号"
                                     child-num-key="num"
                                     width="250">
            </ue-el-table-tree-column>
            <el-table-column show-overflow-tooltip prop="order.shipmentsDate" label="发运日期" width="180">
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="order.extractDateTime" label="提货日期&时间" width="200">
            </el-table-column>
            <el-table-column label="等通知放货" width="120" align="center">
              <template slot-scope="scope">
                <div v-if="scope.row.order">{{scope.row.order.noticeDeliveryStatus === 101022001?'否':(scope.row.order.noticeDeliveryStatus === 101022002? '是':'-')}}</div>
              </template>
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="memberUserName" label="客户" width="80">
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="order.shipmentsContactName" label="发货人" width="80">
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="order.shipmentsRegion" label="发货区域" width="160">
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="order.shipmentsAddress" label="发货地址" width="160">
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="order.sendContactName" label="收货人" width="80">
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="order.sendRegion" label="收货区域" width="160">
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="order.sendAddress" label="收货地址" width="160">
            </el-table-column>
            <el-table-column fixed="right" show-overflow-tooltip prop="order.orderCargos" label="件重体" width="170"
                             :formatter="formatterOrderCargos">
            </el-table-column>
            <el-table-column show-overflow-tooltip width="100" prop="order.remark" label="备注">
            </el-table-column>
          </ue-el-table>
        </div>
        <split-task ref="mySplitTask" :task="selectedOrder" @confirmSplit="confirmSplitHandle"></split-task>
        <split-task ref="myPendingDeliverySplitTask" :task="selectedPendingDeliveryShortTask"
                    @confirmSplit="pendingDeliveryConfirmSplitHandle"></split-task>
      </ue-el-collapse-item>
      <el-collapse-item :title="center.title" name="2">
        <ue-search-bar empty-text="vehicle_task组查询条件未配置" ref="ueSearchVehicleTask" v-model="center.shortTaskSearchCondition" :data="querysVehicleTask" label-width="100px">
        </ue-search-bar>
        <!-- 操作 -->
        <el-col :span="24" style="margin-bottom: 10px">
          <el-col :span="8">
            <el-switch
              v-model="center.shortTaskType"

              >
            </el-switch>
            <el-button type="danger" @click="remove" :disabled="center.noIssuedFlg || (shortTaskTotalNum === 0)">移除
            </el-button>
            <el-button type="primary" @click="issued" :disabled="center.noIssuedFlg || (shortTaskTotalNum === 0)">下发
            </el-button>
            <el-button type="primary" @click="showSetPrice"
                       :disabled="selectedShortTask ==null || selectedShortTask.type==='group' || selectedShortTask.childrenNum>0 || selectedShortTask.issued">
              一口价
            </el-button>
            <el-button type="primary" @click="openCancelDialog" :disabled="center.cancelFlg || (shortTaskTotalNum === 0)">取消
            </el-button>
          </el-col>
          <el-col :span="8">
            <span style="font-size: 16px;margin-left: 50px;">当前选中：{{shortTaskTotalAmount}}件 {{shortTaskTotalWeight.toFixed(2)}}吨 {{shortTaskTotalVolume.toFixed(2)}}方</span>
          </el-col>
          <el-col :span="8" style="text-align: right">
            <el-button type="primary" @click="resetShortTaskSearchCondition">重置</el-button>
            <el-button type="primary" @click="searchShortTask" :disabled="selectVehicle==null">查询</el-button>
          </el-col>
        </el-col>

        <!--列表-->
        <ue-el-table ref="shortTaskTable" :data="center.shortTaskTableData" highlight-current-row border
                     @selection-change="selsShortTaskChange"
                     @select="shortTaskSelect"
                     @current-change="handleShortTaskCurrentChange"
                     height="100%"
                     :row-class-name="tableRowClassName"
                     v-loading="center.shortTaskListLoading" style="width: 100%;">
          <el-table-column fixed type="selection" width="55">
          </el-table-column>
          <ue-el-table-tree-column fixed
                                   :remote="remoteShortTask"
                                   prop="label"
                                   label="订单号"
                                   child-num-key="num"
                                   width="250">
            <template slot-scope="scope">
              <a style="cursor: pointer;text-decoration:underline;"  @click="orderDetail(scope.row)">{{scope.row.label}}</a>
            </template>
          </ue-el-table-tree-column>
          <el-table-column prop="order.orderStatusName" label="订单状态" width="130">
            <template slot-scope="scope">
              <div v-if="scope.row.childrenNum==null && scope.row.order">{{scope.row.order.orderStatusName}}</div>
            </template>
          </el-table-column>
          <el-table-column prop="issued" label="下发状态" width="130">
            <template slot-scope="scope">
              <div v-if="scope.row.childrenNum==null && scope.row.issued===true">已下发</div>
              <div v-else-if="scope.row.childrenNum==null && scope.row.issued===false">待下发</div>
            </template>
          </el-table-column>
          <el-table-column prop="statusName" label="任务状态" width="130">
            <template slot-scope="scope">
              <div v-if="scope.row.childrenNum==null && scope.row.taskType===105003001">{{scope.row.taskExeStatusName}}</div>
              <div v-else-if="scope.row.childrenNum==null && scope.row.taskType===105003002">{{scope.row.deliverTaskExeStatusName}}</div>
            </template>
          </el-table-column>
          <el-table-column prop="receiveName" label="接收状态" width="130">
            <template slot-scope="scope">
              <div v-if="scope.row.childrenNum==null">{{scope.row.receiveName}}</div>
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip prop="order.shipmentsDate" label="发运日期" width="140">
          </el-table-column>
          <el-table-column show-overflow-tooltip prop="order.extractDateTime" label="提货日期&时间" width="200">
          </el-table-column>
          <el-table-column show-overflow-tooltip prop="memberUserName" label="客户" width="80">
          </el-table-column>
          <el-table-column show-overflow-tooltip prop="order.shipmentsRegion" label="发货区域" width="104">
          </el-table-column>
          <el-table-column show-overflow-tooltip prop="order.shipmentsRegion" label="发货地址" width="120">
          </el-table-column>
          <el-table-column show-overflow-tooltip prop="order.sendRegion" label="收货区域" width="104">
          </el-table-column>
          <el-table-column show-overflow-tooltip prop="order.sendAddress" label="收货地址" width="120">
          </el-table-column>
          <el-table-column fixed="right" show-overflow-tooltip prop="order.orderCargos" label="件重体" width="170"
                           :formatter="formatterOrderCargos">
          </el-table-column>
          <el-table-column show-overflow-tooltip width="100" prop="order.remark" label="备注">
          </el-table-column>
        </ue-el-table>
        <el-dialog title="确认下发订单?" :visible.sync="issuedDialogVisible"
          size="tiny">
          <span>即将订单下发给司机{{selectVehicle ? (selectVehicle.driverInfos.length>0?selectVehicle.driverInfos[0].name:'') : ''}} {{selectVehicle ? selectVehicle.plateNumber : ''}}</span>
          <div style="height: 65px;margin-top: 10px;">
            <el-checkbox v-model="driverPriceChecked">设置一口价</el-checkbox>
            <div class="el-message-box__input" v-show="driverPriceChecked">
              <el-input v-model="driverPrice" @change="validateDriverPrice"
                        :class="!!editorErrorMessage ? 'invalid' : ''" placeholder="请输入价格" ref="input"></el-input>
              <div class="el-message-box__errormsg"
                   :style="{ visibility: !!editorErrorMessage ? 'visible' : 'hidden' }">{{ editorErrorMessage }}
              </div>
            </div>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="issuedDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="issuedHandle">确 定</el-button>
          </span>
        </el-dialog>
      </el-collapse-item>
    </el-collapse>
    <!--订单查看Dialog-->
    <el-dialog title="订单查看" :visible.sync="orderDetailSelect" width="80%">
      <order-select :title="orderSelectForm"></order-select>
    </el-dialog>
    <!--取消任务-->
    <el-dialog title="取消任务" :visible.sync="cancelDialog" size="tiny">
      <el-form :key="dialogKey" :model="shortTaskAcceptRefuse" ref="shortTaskAcceptRefuse" style="width: 80%;margin: 0px auto">
        <el-form-item style="text-align: center">
          <label style="font-size: 16px">您正在对
            <span style="color: #169BD5">[{{shortTaskAcceptRefuse.driverName}}] [{{shortTaskAcceptRefuse.plateNumber}}]</span>
            的<span>{{shortTaskAcceptRefuse.taskType == 105003001?"提货":"送货"}}</span>任务进行取消操作</label>
        </el-form-item>
        <el-form-item label="取消原因" prop="remark" :label-width="dialogFormLabelWidth" :rules="[{required: true, type:'string', message: '请描述任务取消原因', trigger: 'blur'}]">
          <el-input type="textarea" v-model="shortTaskAcceptRefuse.remark" :rows="4" placeholder="请描述任务取消原因"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeCancelDialog()">取 消</el-button>
        <el-button type="primary" @click.native="submitCancelDialogForm()" :loading="cancelDialogSubmitLoading">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
import {goodsVehicleStatistics} from '../../api/stowage/ShortBarge';
import {
  addAndIssuedShortTask,
  issuedAndPriceShortTask,
  removeShortTask,
  shortTasks,
  modifyShortTask,
  modifyShortTasks,
  shortTasksSendRegionAndNum,
  shortTasksShipmentsRegionAndNum,
  splitShortTask,
  isCancleSplitShortTask,
  cancleSplitShortTask,
  shortTasksNoPage,
  cancelShortTask
} from '../../api/stowage/shortTask';
import {
  searchAllVehicleInfo,
  saveVehicleInfoTemporary,
  searchVehicleInfoTemporary
} from '../../api/stowage/VehicleManage';
import {resetObjNull, isEmpty} from '../../lib/util.js';
import SplitTask from './split-task/SplitTask.vue';
import OrderSelect from '../order/OrderSelectDialog.vue';
import { getOrderByOrderNumber } from '../../api/order/order.js';
export default{
  data () {
    return {
      orderSelectForm: {},
      orderDetailSelect: false,
      isCancleSplitPendingDeliveryShortTask: false,
      selectedPendingDeliveryShortTask: null,
      activeElTabsItem: '待接货列表',
      isCancleSplitShortTask: false,
      selectedOrder: null,
      driverPriceChecked: false,
      editorErrorMessage: '',
      driverPrice: null,
      issuedDialogVisible: false,
      selectedShortTask: null,
      vehicleIds: [],
      selectVehicle: null,
      isIssued: false,
      left: {
        addVehicleDialogVisible: false,
        vehicleForm: {
          plateNumber: null,
          name: null,
          phone: null
        },
        goodsVehicleStatistics: {
          vehicleNum: 0,
          orderStatistics: {
            orderSum: 0,
            total: 0,
            totalVolume: 0,
            totalWeight: 0
          }
        },
        searchVehicleLoading: false,
        vehicles: [],
        listLoading: false,
        vehicleTableData: [],
        vehicleTableDataTemporary: []
      },
      pendingDeliverySels: [],
      orderSels: [],
      shortTaskSels: [],
      pendingDeliveryTotalAmount: 0,
      pendingDeliveryTotalWeight: 0,
      pendingDeliveryTotalVolume: 0,
      pendingDeliveryTotalNum: 0,
      totalAmount: 0,
      totalWeight: 0,
      totalVolume: 0,
      totalNum: 0,
      shortTaskTotalAmount: 0,
      shortTaskTotalWeight: 0,
      shortTaskTotalVolume: 0,
      shortTaskTotalNum: 0,
      center: {
        pendingDeliveryType: false,
        pendingDeliverySearchCondition: {},
        pendingDeliveryLoading: false,
        pendingDeliveryTableData: [],
        orderType: false,
        activeNames: '1',
        orderSearchCondition: {},
        orderListLoading: false,
        orderTableData: [],
        shortTaskType: false,
        shortTaskSearchCondition: {
          EQ_number: null,
          EQ_memberUserName: null,
          LT_shipmentsDate: null,
          GT_shipmentsDate: null,
          LT_orderDate: null,
          GT_orderDate: null
        },
        noIssuedFlg: false,
        cancelFlg: false, // 默认不可取消操作
        shortTaskTableData: [],
        shortTaskListLoading: false,
        title: '车辆任务详情 (车辆任务：0个/0件/0吨/0方)'
      },
      // 取消s司机短途任务
      isTemporaryDriver: false,
      dialogFormLabelWidth: '100px',
      dialogKey: 0,
      cancelDialogSubmitLoading: false,
      cancelDialog: false,
      shortTaskAcceptRefuse: {
        shortTaskId: '',
        driverName: '',
        plateNumber: '',
        taskType: '',
        remark: ''
      }
    };
  },
  components: {
    SplitTask,
    'order-select': OrderSelect
  },
  methods: {
    openCancelDialog () {
      this.shortTaskAcceptRefuse.plateNumber = this.selectVehicle.plateNumber;
      let driverInfos = this.selectVehicle.driverInfos;
      let selectDriverInfo = driverInfos.length > 0 ? driverInfos[0] : {id: null, name: null, phone: null};
      this.shortTaskAcceptRefuse.driverName = selectDriverInfo.name;
      this.shortTaskSels.map(item => {
        let type = item.type === 'group' ? (!this.center.pendingDeliveryType ? 'send_group' : 'shipments_group') : (item.childrenNum ? 'parent' : '');
        if (isEmpty(type)) {
          this.shortTaskAcceptRefuse.shortTaskId = item.id;
          this.shortTaskAcceptRefuse.taskType = item.taskType;
        }
      });
      if (isEmpty(this.shortTaskAcceptRefuse.shortTaskId)) {
        this.$message('请选择已下发，已接受任务进行取消操作');
        return;
      }
      this.dialogKey = Math.random();
      this.cancelDialog = true;
    },
    closeCancelDialog () {
      resetObjNull(this.shortTaskAcceptRefuse);
      this.cancelDialog = false;
    },
    submitCancelDialogForm () {
      this.$refs['shortTaskAcceptRefuse'].validate((valid) => {
        if (valid) {
          this.cancelDialogSubmitLoading = true;
          cancelShortTask(this.shortTaskAcceptRefuse).then((res) => {
            this.cancelDialogSubmitLoading = false;
            if (res.data.successFlg === true) {
              this.$message('移除成功');
              this.cancelDialog = false;
              this.searchOrder();
              this.searchPendingDeliveryShortTask();
              this.searchShortTask();
            } else {
              this.$message.error(res.data.errorMsg);
            }
          }).catch(function (error) {
            this.cancelDialogSubmitLoading = false;
            console.log(error);
          });
        } else {
          return false;
        }
      });
    },
    tableRowClassName (row, index) {
      if (row.childrenNum > 0) {
        return 'split_order';
      }
      if (row.receiveName === '已取消') {
        return 'split_cancel';
      }
      return '';
    },
    // 待配送列表导出
    waitShortBargeExpress () {
      shortTasksNoPage({
        filters: 'EQ_assign=false;EQ_taskType=105003002;ISNULL_childrenNum;'
      }).then((res) => {
        if (res.data.successFlg) {
          this.$ue.downloadFile(res.data.detailModelList.map(item => [item.number, item.shipmentsDate, item.order.extractDateTime, item.memberUserName, item.order.sendContactName, item.order.shipmentsRegion, item.order.shipmentsAddress, item.order.sendRegion, item.order.sendAddress, item.order.orderCargos[0].volume, item.order.orderCargos[0].weight, item.order.orderCargos[0].amount, item.order.orderCargos[0].remark]), ['任务单号', '发运日期', '提货日期时间', '客户', '发货人', '发货区域', '发货地址', '收货区域', '收货地址', '件积', '重量', '件数', '备注'], '短途调度待配送导出文件');
        } else {
          return this.$message.error('目前暂无数据，无法导出');
        }
      });
    },
    // 待接货列表导出
    shortBargeExpress () {
      shortTasksNoPage({
        filters: 'EQ_assign=false;EQ_taskType=105003001;ISNULL_childrenNum;'
      }).then((res) => {
        if (res.data.successFlg) {
          this.$ue.downloadFile(res.data.detailModelList.map(item => [item.number, item.shipmentsDate, item.order.extractDateTime, item.memberUserName, item.order.sendContactName, item.order.shipmentsRegion, item.order.shipmentsAddress, item.order.sendRegion, item.order.sendAddress, item.order.orderCargos[0].volume, item.order.orderCargos[0].weight, item.order.orderCargos[0].amount, item.order.orderCargos[0].remark]), ['任务单号', '发运日期', '提货日期时间', '客户', '发货人', '发货区域', '发货地址', '收货区域', '收货地址', '件积', '重量', '件数', '备注'], '短途调度待接货导出文件');
        } else {
          return this.$message.error('目前暂无数据，无法导出');
        }
      });
    },
    handlePendingDeliveryCurrentChange (val) {
      this.selectedPendingDeliveryShortTask = val;
      if (val && val.childrenNum !== null) {
        isCancleSplitShortTask(val.id).then(res => {
          if (res.data.successFlg) {
            this.isCancleSplitPendingDeliveryShortTask = res.data.obj;
          }
        });
      } else {
        this.isCancleSplitPendingDeliveryShortTask = false;
      }
    },
    handleOrderCurrentChange (val) {
      this.selectedOrder = val;
      if (val && val.childrenNum !== null) {
        isCancleSplitShortTask(val.id).then(res => {
          if (res.data.successFlg) {
            this.isCancleSplitShortTask = res.data.obj;
          }
        });
      } else {
        this.isCancleSplitShortTask = false;
      }
    },
    pendingDeliveryConfirmSplitHandle (data) {
      splitShortTask(this.selectedPendingDeliveryShortTask.id, data)
        .then(res => {
          if (res.data.successFlg) {
            this.searchPendingDeliveryShortTask();
            this.$message('拆单成功');
          } else {
            this.$message.error(res.data.errorMsg);
          }
        });
    },
    confirmSplitHandle (data) {
      splitShortTask(this.selectedOrder.id, data)
        .then(res => {
          if (res.data.successFlg) {
            this.searchOrder();
            this.$message('拆单成功');
          } else {
            this.$message.error(res.data.errorMsg);
          }
        });
    },
    confirmSplit () {
      this.$refs.mySplitTask.show();
    },
    pendingDeliveryConfirmSplit () {
      this.$refs.myPendingDeliverySplitTask.show();
    },
    removeSplit () {
      this.$confirm('您确认取消该订单的拆单?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        cancleSplitShortTask(this.selectedOrder.id)
          .then(res => {
            if (res.data.successFlg) {
              this.$message('取消拆单成功');
              this.searchOrder();
            } else {
              this.$message.error(res.data.errorMsg);
            }
          });
      }).catch(() => {
      });
    },
    removePendingDeliverySplit () {
      this.$confirm('您确认取消该订单的拆单?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        cancleSplitShortTask(this.selectedPendingDeliveryShortTask.id)
          .then(res => {
            if (res.data.successFlg) {
              this.$message('取消拆单成功');
              this.searchPendingDeliveryShortTask();
            } else {
              this.$message.error(res.data.errorMsg);
            }
          });
      }).catch(() => {
      });
    },
    handleShortTaskCurrentChange (val) {
      this.selectedShortTask = val;
    },
    showSetPrice () {
      this.$prompt('请输入价格', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^(-)?\d+(\.\d+)?$/,
        inputErrorMessage: '请输入数字'
      }).then(({value}) => {
        modifyShortTask(this.selectedShortTask.id, {driverPrice: value})
          .then(res => {
            if (res.data.successFlg) {
              this.$message('一口价设置成功');
            } else {
              this.$message.error(res.data.errorMsg);
            }
          });
      }).catch(() => {
      });
    },
    pendingDeliverySelect (sel, row) {
      this.parentSelect('pendingDeliveryTable', sel, row);
    },
    orderSelect (sel, row) {
      this.parentSelect('orderTable', sel, row);
    },
    shortTaskSelect (sel, row) {
      this.parentSelect('shortTaskTable', sel, row);
    },
    parentSelect (ref, sel, row) {
      let self = this;
      let ids = sel.map(i => i.id);
      const traverseCheckedChilNodes = function (node) {
        const childNodes = node.children;
        if (childNodes) {
          childNodes.forEach((child) => {
            if (ids.indexOf(child.id) === -1) {
              self.$refs[ref].toggleRowSelection(child);
            }
            traverseCheckedChilNodes(child);
          });
        }
      };
      const traverseUnCheckChilNodes = function (node) {
        const childNodes = node.children;
        if (childNodes) {
          childNodes.forEach((child) => {
            if (ids.indexOf(child.id) > -1) {
              self.$refs[ref].toggleRowSelection(child, false);
            }
            traverseUnCheckChilNodes(child);
          });
        }
      };

      const traverseParent = function (node, checked = true) {
        let id = node.$pid;
        while (id) {
          if (checked) {
            let children = sel.filter(item => {
              return item.$pid === id;
            });
            let parents = self.$refs[ref].store.states.data.filter(item => {
              return item.id === id;
            });
            if (parents.length > 0 && parents[0].children.length === children.length) {
              self.$refs[ref].toggleRowSelection(parents[0]);
              id = parents[0].$pid;
            } else {
              id = null;
            }
          } else {
            let parents = sel.filter(item => {
              return item.id === id;
            });
            if (parents.length > 0) {
              self.$refs[ref].toggleRowSelection(parents[0], false);
              id = parents[0].$pid;
            } else {
              id = null;
            }
          }
        }
      };
      if (ids.indexOf(row.id) > -1) {
        if (row.children) {
          traverseCheckedChilNodes(row);
        } else {
          traverseParent(row, true);
        }
      } else {
        if (row.children) {
          traverseUnCheckChilNodes(row);
        } else {
          traverseParent(row, false);
        }
      }
    },
    // 加载历史临时车辆
    loadVehicleTemporary () {
      let filters = 'EQ_usage=109010002';
      searchVehicleInfoTemporary({
        filters: filters,
        size: 6,
        page: 1
      }).then(res => {
        if (res.data.successFlg === true) {
          this.left.vehicleTableDataTemporary = res.data.detailModelList;
        }
      });
    },
    // 选择历史使用临时车辆
    selectVehicleInfoTemporary (item) {
      this.left.vehicleForm.plateNumber = item.plateNumber;
      this.left.vehicleForm.name = item.contactPerson;
      this.left.vehicleForm.phone = item.contactPhone;
    },
    // 新增临时车辆（保存数据库）
    saveVehicle () {
      this.$refs.addVehicleForm.validate((valid) => {
        if (valid) {
          let item = {
            plateNumber: this.left.vehicleForm.plateNumber,
            driverInfos: [{
              name: this.left.vehicleForm.name,
              phone: this.left.vehicleForm.phone
            }]
          };
            // 保存临时车辆信息
          let vehicleInfoTemporary = {
            plateNumber: this.left.vehicleForm.plateNumber,
            contactPerson: this.left.vehicleForm.name,
            contactPhone: this.left.vehicleForm.phone,
            usage: 109010002
          };
          saveVehicleInfoTemporary(vehicleInfoTemporary).then((res) => {
            if (res.data.successFlg) {
              item.id = res.data.obj.id;
              console.log(item);
              this.left.vehicleTableData.push(item);
              this.left.addVehicleDialogVisible = false;
            } else {
              this.$message.error(res.data.errorMsg);
            }
          });
        }
      });
    },
    addPendingDeliveryShortTask () {
      this.optPendingDeliveryOrder('105003002', this.getPendingDeliveryFilters(), this.pendingDeliverySels, {assign: true}, () => {
        this.searchPendingDeliveryShortTask();
        this.searchShortTask();
      });
    },
    addPendingDeliveryShortTaskAndIssued () {
      this.optPendingDeliveryOrder('105003002', this.getPendingDeliveryFilters(), this.pendingDeliverySels, {assign: true, issued: true}, () => {
        this.searchPendingDeliveryShortTask();
        this.searchShortTask();
      });
    },
    addVehicle () {
      if (this.$refs.addVehicleForm) {
        this.$refs.addVehicleForm.resetFields();
      }
      this.left.addVehicleDialogVisible = true;
      this.loadVehicleTemporary();
    },
    addShortTask () {
      this.optOrder('105003001', this.getOrderTableFilters(), this.orderSels, {assign: true}, () => {
        this.searchOrder();
        this.searchShortTask();
      });
    },
    addShortTaskAndIssued () {
      this.optOrder('105003001', this.getOrderTableFilters(), this.orderSels, {assign: true, issued: true}, () => {
        this.searchOrder();
        this.searchShortTask();
      });
    },
    optPendingDeliveryOrder (taskType, filters, sels, params, fn) {
      if (this.selectVehicle == null) {
        this.$message({
          message: '请选中一辆车'
        });
      } else {
        let ids = sels.map(item => {
          return {
            id: item.id,
            type: item.type === 'group' ? (!this.center.pendingDeliveryType ? 'send_group' : 'shipments_group') : (item.childrenNum ? 'parent' : '')
          };
        });
        params.vehicleId = this.selectVehicle.id;
        params.plateNumber = this.selectVehicle.plateNumber;
        let driverInfos = this.selectVehicle.driverInfos;
        let selectDriverInfo = driverInfos.length > 0 ? driverInfos[0] : {id: null, name: null, phone: null};
        params.driverInfoId = selectDriverInfo.id;
        params.driverInfoName = selectDriverInfo.name;
        params.driverInfoPhone = selectDriverInfo.phone;
        addAndIssuedShortTask(taskType, filters, ids, params)
          .then(res => {
            if (res.data.successFlg) {
              this.$message.success('将' + this.pendingDeliveryTotalNum + '个订单添加到车辆' + this.selectVehicle.plateNumber + '成功');
              if (fn) {
                fn();
              }
            } else {
              this.$message.error(res.data.errorMsg);
            }
          });
      }
    },
    optOrder (taskType, filters, sels, params, fn) {
      if (this.selectVehicle == null) {
        this.$message({
          message: '请选中一辆车'
        });
      } else {
        let ids = sels.map(item => {
          return {
            id: item.id,
            type: item.type === 'group' ? (this.center.orderType ? 'send_group' : 'shipments_group') : (item.childrenNum ? 'parent' : '')
          };
        });
        params.vehicleId = this.selectVehicle.id;
        params.plateNumber = this.selectVehicle.plateNumber;
        let driverInfos = this.selectVehicle.driverInfos;
        let selectDriverInfo = driverInfos.length > 0 ? driverInfos[0] : {id: null, name: null, phone: null};
        params.driverInfoId = selectDriverInfo.id;
        params.driverInfoName = selectDriverInfo.name;
        params.driverInfoPhone = selectDriverInfo.phone;
        addAndIssuedShortTask(taskType, filters, ids, params)
          .then(res => {
            if (res.data.successFlg) {
              this.$message.success('将' + this.totalNum + '个订单添加到车辆' + this.selectVehicle.plateNumber + '成功');
              if (fn) {
                fn();
              }
            } else {
              this.$message.error(res.data.errorMsg);
            }
          });
      }
    },
    optShortTask (params, fn) {
      if (this.shortTaskSels.length > 0) {
        let ids = this.shortTaskSels.map(item => {
          return {
            id: item.id,
            type: item.type === 'group' ? (this.center.shortTaskType ? 'send_group' : 'shipments_group') : (item.childrenNum ? 'parent' : '')
          };
        });
        this.handleModifyShortTasks(ids, params, fn);
      } else {
        this.$message({
          message: '请选中一些车辆任务'
        });
      }
    },
    remove () {
      let ids = this.shortTaskSels.map(item => {
        return {
          id: item.id,
          type: item.type === 'group' ? (this.center.shortTaskType ? 'send_group' : 'shipments_group') : (item.childrenNum ? 'parent' : '')
        };
      });
      removeShortTask(this.selectVehicle.id, 'NOTEQ_taskExeStatus=101013005;EQ_assign=true;' + this.getShortTaskFilters(), ids, {issued: false, assign: false, receive: 101019001})
        .then(res => {
          if (res.data.successFlg) {
            this.$message('移除成功');
            this.searchOrder();
            this.searchPendingDeliveryShortTask();
            this.searchShortTask();
          } else {
            this.$message.error(res.data.errorMsg);
          }
        });
    },
    optIssuedAndPriceShortTask (param, fn) {
      let ids = this.shortTaskSels.map(item => {
        return {
          id: item.id,
          type: item.type === 'group' ? (this.center.shortTaskType ? 'send_group' : 'shipments_group') : (item.childrenNum ? 'parent' : '')
        };
      });
      issuedAndPriceShortTask(this.selectVehicle.id, this.getShortTaskFilters(), ids, param)
        .then(res => {
          if (res.data.successFlg) {
            this.searchShortTask();
            if (fn) {
              fn();
            }
          } else {
            this.$message.error(res.data.errorMsg);
          }
        });
    },
    issued () {
      this.driverPrice = null;
      this.issuedDialogVisible = true;
      this.driverPriceChecked = false;
    },
    validateDriverPrice () {
      if (this.$ue.regExps.isNum.test(this.driverPrice)) {
        this.editorErrorMessage = null;
        return true;
      } else {
        this.editorErrorMessage = '请输入数字';
        return false;
      }
    },
    issuedHandle () {
      let params = {issued: true};
      if (this.driverPriceChecked) {
        if (this.validateDriverPrice()) {
          params.driverPrice = this.driverPrice;
        } else {
          return;
        }
      }
      this.optIssuedAndPriceShortTask(params, () => {
        this.issuedDialogVisible = false;
        this.$message('下发成功');
      });
    },
    pendingDeliveryChange (sels) {
      this.pendingDeliverySels = sels;
    },
    selsOrderChange (sels) {
      this.orderSels = sels;
    },
    selsShortTaskChange (sels) {
      this.shortTaskSels = sels;
    },
    handleCurrentChange (val) {
      if (val) {
        this.isIssued = val.driverInfos.length > 0;
        this.selectVehicle = val;
        // 临时司机 按钮控制（ ‘添加并下发’按钮 不能‘添加’按钮）
        if (val.driverInfos.length && isEmpty(val.driverInfos[0].id)) {
          this.isTemporaryDriver = true;
        } else {
          this.isTemporaryDriver = false;
        }
        this.resetShortTaskSearchCondition();
        this.loadShortTask('');
      } else {
        this.isIssued = false;
        this.selectVehicle = null;
        this.center.shortTaskTableData = [];
        this.center.title = '车辆任务详情 (车辆任务：0个/0件/0吨/0方)';
      }
    },
    searchVehicle (query) {
      if (query !== '' && query.length > 2) {
        this.searchVehicleLoading = true;
        this.loadSearchVehicle('LIKE_plateNumber=' + query);
      }
    },
    loadSearchVehicle (filters = '') {
      this.searchVehicleLoading = true;
      searchAllVehicleInfo({
        filters: filters,
        sorts: ''
      }).then(res => {
        if (res.data.successFlg === true) {
          this.searchVehicleLoading = false;
          this.left.vehicles = res.data.detailModelList;
        }
      });
    },
    handleModifyShortTasks (id, params, fn) {
      modifyShortTasks(id, params)
        .then(res => {
          if (res.data.successFlg) {
            if (fn) {
              fn();
            }
          } else {
            this.$message.error(res.data.errorMsg);
          }
        });
    },
    loadVehicle (filters) {
      this.listLoading = true;
      searchAllVehicleInfo({
        filters: filters,
        size: 30,
        page: 1
      }).then(res => {
        if (res.data.successFlg === true) {
          this.listLoading = false;
          this.left.vehicleTableData = res.data.detailModelList;
        }
      });
    },
    loadShortTask (filters) {
      this.center.shortTaskListLoading = true;
      if (this.center.shortTaskType) {
        this.loadShortTasksSendRegionAndNum('EQ_assign=true;ISNULL_childrenNum;NOTEQ_taskExeStatus=101013005;EQ_vehicleId=' + this.selectVehicle.id + ';' + filters, data => {
          this.center.shortTaskListLoading = false;
          this.center.shortTaskTableData = data;
          this.handleCenterTitle(data);
        });
      } else {
        this.loadShortTasksShipmentsRegionAndNum('EQ_assign=true;ISNULL_childrenNum;NOTEQ_taskExeStatus=101013005;EQ_vehicleId=' + this.selectVehicle.id + ';' + filters, data => {
          this.center.shortTaskListLoading = false;
          this.center.shortTaskTableData = data;
          this.handleCenterTitle(data);
        });
      }
    },
    handleCenterTitle (items) {
      let totalAmount = 0;
      let totalWeight = 0;
      let totalVolume = 0;
      let totalNum = 0;
      items.forEach(item => {
        totalNum += item.num;
        totalAmount += item.amount;
        totalWeight += item.weight;
        totalVolume += item.volume;
      });
      this.center.title = '车辆任务详情 (车辆任务：' + totalNum + '个/' + totalAmount + '件/' + totalWeight.toFixed(2) + '吨/' + totalVolume.toFixed(2) + '方)';
    },
    resetShortTaskSearchCondition () {
      this.$refs.ueSearchVehicleTask.reset();
    },
    resetPendingDeliveryShortTaskCondition () {
      this.$refs.ueSearchBaristribution.reset();
    },
    resetOrderCondition () {
      this.$refs.ueSearchBarReceiving.reset();
    },
    getPendingDeliveryFilters () {
      return this.$ue.objToFilter(this.center.pendingDeliverySearchCondition);
    },
    searchPendingDeliveryShortTask () {
      this.loadPendingDeliveryTableData(this.getPendingDeliveryFilters());
    },
    getOrderTableFilters () {
      return this.$ue.objToFilter(this.center.orderSearchCondition);
    },
    searchOrder () {
      this.loadOrderTableData(this.getOrderTableFilters());
    },
    getShortTaskFilters () {
      return this.$ue.objToFilter(this.center.shortTaskSearchCondition);
    },
    searchShortTask () {
      this.loadShortTask(this.getShortTaskFilters());
    },
    formatterOrderCargos (row) {
      return row.amount + '件/' + row.weight.toFixed(2) + '吨/' + row.volume.toFixed(2) + '方';
    },
    loadGoodsVehicleStatistics () {
      goodsVehicleStatistics()
        .then(res => {
          if (res.data.successFlg) {
            this.left.goodsVehicleStatistics.vehicleNum = res.data.obj.vehicleNum || 0;
            this.left.goodsVehicleStatistics.orderStatistics.orderSum = res.data.obj.orderStatistics.orderSum || 0;
            this.left.goodsVehicleStatistics.orderStatistics.total = res.data.obj.orderStatistics.total || 0;
            this.left.goodsVehicleStatistics.orderStatistics.totalVolume = res.data.obj.orderStatistics.totalVolume || 0;
            this.left.goodsVehicleStatistics.orderStatistics.totalWeight = res.data.obj.orderStatistics.totalWeight || 0;
          }
        });
    },
    remotePendingDelivery (row, callback) {
      let filters = 'EQ_assign=false;EQ_taskType=105003002;' + this.$ue.objToFilter(this.center.pendingDeliverySearchCondition) + ';';
      let orFilters;
      let depth = 0;
      if (row.type === 'group') {
        let o = {};
        Object.keys(this.center.pendingDeliverySearchCondition).forEach(k => {
          let ks = k.split('_');
          o[ks[0] + '_LEFT_children.' + ks[1]] = this.center.pendingDeliverySearchCondition[k];
        });
        orFilters = 'EQ_LEFT_children.taskType=105003002;EQ_LEFT_children.assign=false;' + this.$ue.objToFilter(o) + ';';
        filters += ';ISNULL_childrenNum;ISNULL_parent;';
        if (!this.center.pendingDeliveryType) {
          filters += ';EQ_sendCountyId=' + row.id + ';';
          orFilters += ';EQ_LEFT_children.sendCountyId=' + row.id + ';';
        } else {
          filters += ';EQ_shipmentsCountyId=' + row.id + ';';
          orFilters += ';EQ_LEFT_children.shipmentsCountyId=' + row.id + ';';
        }
        depth = 1;
      } else {
        filters += 'EQ_parent.id=' + row.id;
        if (!this.center.pendingDeliveryType) {
          filters += ';EQ_sendCountyId=' + row.parent_id + ';';
        } else {
          filters += ';EQ_shipmentsCountyId=' + row.parent_id + ';';
        }
        depth = 2;
      }
      shortTasks({
        filters: filters,
        orFilters: orFilters,
        sorts: '-createDate'
      }).then(res => {
        if (res.data.successFlg === true) {
          const detailModelList = res.data.detailModelList;
          detailModelList.forEach(item => {
            item.parent_id = row.id;
            item.depth = depth;
            if (item.childrenNum) {
              item.num = item.childrenNum;
              item.label += ('(拆-' + item.childrenNum + ')');
            }
          });
          callback(detailModelList);
        }
      });
    },
    remote (row, callback) {
      let filters = 'EQ_assign=false;EQ_taskType=105003001;' + this.$ue.objToFilter(this.center.orderSearchCondition) + ';';
      let orFilters;
      let depth = 0;
      if (row.type === 'group') {
        let o = {};
        Object.keys(this.center.orderSearchCondition).forEach(k => {
          let ks = k.split('_');
          o[ks[0] + '_LEFT_children.' + ks[1]] = this.center.orderSearchCondition[k];
        });
        orFilters = 'EQ_LEFT_children.taskType=105003001;EQ_LEFT_children.assign=false;' + this.$ue.objToFilter(o) + ';';
        filters += ';ISNULL_childrenNum;ISNULL_parent;';
        if (!this.center.orderType) {
          filters += ';EQ_shipmentsCountyId=' + row.id + ';';
          orFilters += ';EQ_LEFT_children.shipmentsCountyId=' + row.id + ';';
        } else {
          filters += ';EQ_sendCountyId=' + row.id + ';';
          orFilters += ';EQ_LEFT_children.sendCountyId=' + row.id + ';';
        }
        depth = 1;
      } else {
        filters += 'EQ_parent.id=' + row.id;
        if (!this.center.orderType) {
          filters += ';EQ_shipmentsCountyId=' + row.parent_id + ';';
        } else {
          filters += ';EQ_sendCountyId=' + row.parent_id + ';';
        }
        depth = 2;
      }
      shortTasks({
        filters: filters,
        orFilters: orFilters,
        sorts: '-createDate'
      }).then(res => {
        if (res.data.successFlg === true) {
          const detailModelList = res.data.detailModelList;
          detailModelList.forEach(item => {
            item.parent_id = row.id;
            item.depth = depth;
            if (item.childrenNum) {
              item.num = item.childrenNum;
              item.label += ('(拆-' + item.childrenNum + ')');
            }
          });
          callback(detailModelList);
        }
      });
    },
    remoteShortTask (row, callback) {
      let filters = 'EQ_assign=true;NOTEQ_taskExeStatus=101013005;EQ_vehicleId=' + this.selectVehicle.id + ';' + this.$ue.objToFilter(this.center.shortTaskSearchCondition) + ';';
      let orFilters;
      let depth = 0;
      if (row.type === 'group') {
        let o = {};
        Object.keys(this.center.shortTaskSearchCondition).forEach(k => {
          let ks = k.split('_');
          o[ks[0] + '_LEFT_children.' + ks[1]] = this.center.shortTaskSearchCondition[k];
        });
        orFilters = 'EQ_LEFT_children.assign=true;NOTEQ_LEFT_children.taskExeStatus=101013005;EQ_LEFT_children.vehicleId=' + this.selectVehicle.id + ';' + this.$ue.objToFilter(o) + ';';

        filters += ';ISNULL_childrenNum;ISNULL_parent;';
        if (!this.center.shortTaskType) {
          filters += ';EQ_shipmentsCountyId=' + row.id + ';';
          orFilters += ';EQ_LEFT_children.shipmentsCountyId=' + row.id + ';';
        } else {
          filters += ';EQ_sendCountyId=' + row.id + ';';
          orFilters += ';EQ_LEFT_children.sendCountyId=' + row.id + ';';
        }
        depth = 1;
      } else {
        filters += 'EQ_parent.id=' + row.id;
        if (!this.center.shortTaskType) {
          filters += ';EQ_shipmentsCountyId=' + row.parent_id + ';';
        } else {
          filters += ';EQ_sendCountyId=' + row.parent_id + ';';
        }
        depth = 2;
      }
      shortTasks({
        filters: filters,
        orFilters: orFilters,
        sorts: '-createDate'
      }).then(res => {
        if (res.data.successFlg === true) {
          res.data.detailModelList.forEach(item => {
            item.parent_id = row.id;
            item.depth = depth;
            if (item.childrenNum) {
              item.num = item.childrenNum;
              item.label += ('(拆-' + item.childrenNum + ')');
            }
            if (item.taskType) {
              item.icon = item.taskType === 105003001 ? 'icon iconfont ali_icon-ti' : 'icon iconfont ali_icon-song';
            }
          });
          callback(res.data.detailModelList);
        }
      });
    },
    loadOrderTableData (filters) {
      this.center.orderListLoading = true;
      if (this.center.orderType) {
        this.loadShortTasksSendRegionAndNum('EQ_assign=false;ISNULL_childrenNum;EQ_taskType=105003001;' + filters, data => {
          this.center.orderListLoading = false;
          this.center.orderTableData = data;
        });
      } else {
        this.loadShortTasksShipmentsRegionAndNum('EQ_assign=false;ISNULL_childrenNum;EQ_taskType=105003001;' + filters, data => {
          this.center.orderListLoading = false;
          this.center.orderTableData = data;
        });
      }
    },
    loadPendingDeliveryTableData (filters) {
      this.center.pendingDeliveryLoading = true;
      if (!this.center.pendingDeliveryType) {
        this.loadShortTasksSendRegionAndNum('EQ_assign=false;ISNULL_childrenNum;EQ_taskType=105003002;' + filters, data => {
          this.center.pendingDeliveryLoading = false;
          this.center.pendingDeliveryTableData = data;
        });
      } else {
        this.loadShortTasksShipmentsRegionAndNum('EQ_assign=false;ISNULL_childrenNum;EQ_taskType=105003002;' + filters, data => {
          this.center.pendingDeliveryLoading = false;
          this.center.pendingDeliveryTableData = data;
        });
      }
    },
    loadShortTasksSendRegionAndNum (filters, fn) {
      shortTasksSendRegionAndNum({
        filters: filters
      }).then(res => {
        if (res.data.successFlg === true) {
          fn(res.data.detailModelList.map(item => {
            item.type = 'group';
            item.depth = 0;
            return item;
          }));
        }
      });
    },
    loadShortTasksShipmentsRegionAndNum (filters, fn) {
      shortTasksShipmentsRegionAndNum({
        filters: filters
      }).then(res => {
        if (res.data.successFlg === true) {
          fn(res.data.detailModelList.map(item => {
            item.type = 'group';
            item.depth = 0;
            return item;
          }));
        }
      });
    },
    /**
       * 查看订单
       */
    orderDetail (val) {
      if (val.depth === 0) {
        this.orderDetailSelect = false;
      } else {
        console.log(val);
        this.orderDetailSelect = true;
        getOrderByOrderNumber(val.orderNum).then((res) => {
          if (res.data.successFlg) {
            this.orderSelectForm = res.data.obj;
          }
        });
      }
    }
  },
  watch: {
    'center.pendingDeliveryType': {
      handler (val) {
        this.loadPendingDeliveryTableData(this.getPendingDeliveryFilters());
      },
      deep: true
    },
    'center.orderType': {
      handler (val) {
        this.loadOrderTableData(this.getOrderTableFilters());
      },
      deep: true
    },
    'center.shortTaskType': {
      handler (val) {
        if (this.selectVehicle) {
          this.loadShortTask(this.getShortTaskFilters());
        }
      },
      deep: true
    },
    vehicleIds: function (ids) {
      if (ids.length > 0) {
        this.loadVehicle('IN_id=' + ids.join(','));
      } else {
        this.loadVehicle('');
      }
    },
    pendingDeliverySels (sels) {
      let ids = sels.filter(item => (item.type === 'group' || item.childrenNum > 0)).map(i => i.id);
      let totalAmount = 0;
      let totalWeight = 0;
      let totalVolume = 0;
      let totalNum = 0;
      sels.forEach(item => {
        if (item.type === 'group') {
          totalAmount += item.amount;
          totalWeight += item.weight;
          totalVolume += item.volume;
          totalNum += item.num;
        } else {
          if (ids.indexOf(item.parent_id) === -1 && ids.indexOf(item.pid) === -1) {
            totalAmount += item.amount;
            totalWeight += item.weight;
            totalVolume += item.volume;
            totalNum += (item.childNodeNum || 1);
          }
        }
      });
      this.pendingDeliveryTotalAmount = totalAmount;
      this.pendingDeliveryTotalWeight = totalWeight;
      this.pendingDeliveryTotalVolume = totalVolume;
      this.pendingDeliveryTotalNum = totalNum;
    },
    orderSels: function (sels) {
      let ids = sels.filter(item => (item.type === 'group' || item.childrenNum > 0)).map(i => i.id);
      let totalAmount = 0;
      let totalWeight = 0;
      let totalVolume = 0;
      let totalNum = 0;
      sels.forEach(item => {
        if (item.type === 'group') {
          totalAmount += item.amount;
          totalWeight += item.weight;
          totalVolume += item.volume;
          totalNum += item.num;
        } else {
          if (ids.indexOf(item.parent_id) === -1 && ids.indexOf(item.pid) === -1) {
            totalAmount += item.amount;
            totalWeight += item.weight;
            totalVolume += item.volume;
            totalNum += (item.childNodeNum || 1);
          }
        }
      });
      this.totalAmount = totalAmount;
      this.totalWeight = totalWeight;
      this.totalVolume = totalVolume;
      this.totalNum = totalNum;
    },
    shortTaskSels (sels) {
      let ids = sels.filter(item => item.type === 'group' || item.childrenNum > 0).map(i => i.id);
      this.center.noIssuedFlg = false;
      this.center.cancelFlg = false;
      this.center.issuedShortTaskBtnDisabled = false;
      let totalAmount = 0;
      let totalWeight = 0;
      let totalVolume = 0;
      let totalNum = 0;
      sels.forEach(item => {
        this.center.noIssuedFlg = (this.center.noIssuedFlg || (item.issued && item.receive === 101019002));
        if (item.childrenNum !== undefined && item.childrenNum == null) {
          this.center.cancelFlg = (this.center.cancelFlg || (item.issued === false || item.receive === 101019001 || item.receive === 101019003 || item.receive === 101019004));
        }
        if (item.type === 'group') {
          totalAmount += item.amount;
          totalWeight += item.weight;
          totalVolume += item.volume;
          totalNum += item.num;
        } else {
          let v = item;
          if (ids.indexOf(item.parent_id) === -1 && v) {
            totalAmount += v.amount;
            totalWeight += v.weight;
            totalVolume += v.volume;
            totalNum += (item.childNodeNum || 1);
          }
        }
      });
      this.shortTaskTotalNum = totalNum;
      this.shortTaskTotalAmount = totalAmount;
      this.shortTaskTotalWeight = totalWeight;
      this.shortTaskTotalVolume = totalVolume;
    }
  },
  computed: {
    btns () {
      return this.$store.state.btns[this.$route.path] || [];
    },
    querysReceiving () {
      return this.$store.state.querys[this.$route.path + '#receiving'] || [];
    },
    querysDistribution () {
      return this.$store.state.querys[this.$route.path + '#distribution'] || [];
    },
    querysVehicleTask () {
      return this.$store.state.querys[this.$route.path + '#vehicle_task'] || [];
    }
  },
  mounted () {
    this.loadVehicle('IN_usage=109010001,109010002');
    this.loadOrderTableData('');
    this.loadPendingDeliveryTableData('');
    this.loadSearchVehicle('IN_usage=109010001,109010002');
    this.loadGoodsVehicleStatistics();
  }
};
</script>
